﻿using ThomasGIS.Exceptions;
using ThomasGIS.Geometries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ThomasGIS.Geometries
{
    public class Point : GeometryBase, IPoint
    {
        public double X { get; set; }
        public double Y { get; set; }

        public Point(double x, double y) 
        {
            X = x;
            Y = y;
        }

        public Point(string wkt)
        {
            // "POINT (x y)"
            wkt = wkt.ToUpper();
            string subTypeString = wkt.Substring(0, 5);

            if (subTypeString != "POINT")
            {
                throw new Exception("不符合的WKT字符串类型");
            }

            // 防止用户输入的WKT字符串不标准
            try
            {
                // 移除POINT标识
                string wktContent = wkt.Substring(5, wkt.Length - 5);
                // 移除前后可能存在的空格
                wktContent = wktContent.Trim();
                // 移除前后括号
                wktContent = wktContent.Substring(1, wktContent.Length - 2);
                // 按空格划分x和y
                string[] coordinates = wkt.Split(' ');
                // 赋值
                X = Convert.ToDouble(coordinates[0]);
                Y = Convert.ToDouble(coordinates[1]);
            }
            catch (Exception exception)
            {
                throw new Exception("WKT字符串错误");
            }
        }

        public Point(Point point)
        {
            X = point.X;
            Y = point.Y;
        }

        public static Point ParseWkt(string wkt)
        {
            return new Point(wkt);
        }

        public string ExportToWkt() 
        {
            StringBuilder wktBuilder = new StringBuilder();
            wktBuilder.Append("POINT (");
            wktBuilder.Append(X);
            wktBuilder.Append(" ");
            wktBuilder.Append(Y);
            wktBuilder.Append(")");
            return wktBuilder.ToString();
        }

        public override int ContentLength() 
        {
            return 2 + 4 + 4;
        }

        public override int GetFeatureType()
        {
            return 1;
        }

        public double GetX()
        {
            return this.X;
        }

        public double GetY()
        {
            return this.Y;
        }

        public bool SetX(double x)
        {
            this.X = x;
            return true;
        }

        public bool SetY(double y)
        {
            this.Y = y;
            return true;
        }
    }
}
